package com.warrior.util;

import com.warrior.Exception.ProjectException;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class MD5Util {
    
    /**
     * Logger for this class
     */
    private static final Logger logger = LogManager.getLogger(MD5Util.class.getName());
    
    /**
    
      * 创建一个新的实例 MD5Util. 
      */
    private MD5Util(){
        
    }

    /**
      * getMD5
      * 
      * @Title: getMD5
      * @Description: 生成MD5方式的加密内容
      * @param content
      * @return
      * @throws ProjectException
      */
    public static String getMD5(String content) throws ProjectException{
        try {
            MessageDigest digest = MessageDigest.getInstance("MD5");
            digest.update(content.getBytes());
            return getHashString(digest);
        } catch (NoSuchAlgorithmException e) {
            logger.error(e,e.fillInStackTrace());
            throw new ProjectException(e.getMessage());
        }
    }
 
    /**
      * getHashString
      * @Title: getHashString
      * @Description: 获取hashString
      * @param digest
      * @return
      */
    private static String getHashString(MessageDigest digest) {
        StringBuilder builder = new StringBuilder();
        for (byte b : digest.digest()) {
            builder.append(Integer.toHexString((b >> 4) & 0xf));
            builder.append(Integer.toHexString(b & 0xf));
        }
        return builder.toString();
    }
}
